<template>
  <router-link :to="{ path: '/Images' }" class="nav-link">/自动化测试截图</router-link>
  <van-nav-bar title="待办事项列表" fixed />
  <div class="todo-container">
    <h1>待办事项列表</h1>
    <TodoInput @add-todo="addTodo" />
    <ul>
      <TodoItem v-for="(todo, index) in todos" :key="index" :todo="todo" :index="index" @remove-todo="removeTodo"
        @update-todo="updateTodo" />
    </ul>
    <p v-if="remainingTodos === 0">暂无任务</p>
    <p v-else>剩余 {{ remainingTodos }} 项任务。</p>
    <TodoClearButton @clear-todos="clearTodos" />
    <van-button type="danger" @click="handleLogout" style="margin-top: 20px;">退出登录</van-button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import TodoInput from '../components/TodoInput.vue';
import TodoItem from '../components/TodoItem.vue';
import TodoClearButton from '../components/TodoClearButton.vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import { NavBar, Button, Toast } from 'vant';

// 注册 Vant 组件
const components = {
  [NavBar.name]: NavBar,
  [Button.name]: Button
};

const todos = ref([]);

const remainingTodos = computed(() => {
  return todos.value.length;
});

function addTodo(todo) {
  todos.value.push(todo);
}

function removeTodo(index) {
  todos.value.splice(index, 1);
}

function clearTodos() {
  todos.value = [];
}

function updateTodo({ index, newTodo }) {
  todos.value[index] = newTodo;
}

console.log('TodoList component is mounted');

const router = useRouter();
const authStore = useAuthStore();

const handleLogout = () => {
  authStore.logout();
  router.push('/login');
  Toast.success('已退出登录');
};
</script>

<style scoped>
.todo-container {
  font-family: Arial, sans-serif;
  padding-top: 50px; /* 为固定导航栏留出空间 */
}
.nav-link {
  text-decoration: none;
  color: #333;
  font-weight: bold;
}
.logout-btn {
  padding: 8px 16px;
}
p {
  margin-top: 20px;
  font-size: 18px;
}
</style>